<template>
    <span class="sendsms-wrap" @click="sendCodeFun">{{
        codeStatus === 0 ? codeText : codeValue + "s"
    }}</span>
</template>

<script>
import _test from "@/utils/test";
export default {
    name: "sendSms",
    props: {
        api: {
            type: String,
            default: "/api/sendSms",
        },
        apiMobileName: {
            type: String,
            default: "mobile",
        },
        mobile: {
            type: [Number, String],
            default: 0,
        },
    },
    data() {
        return {
            codeText: "获取验证码",
            codeValue: -1,
            codeStatus: 0,
            timeFun:null
        };
    },
    methods: {
        async sendCodeFun() {
            if (this.codeStatus == 1) {
                return false;
            }
            if (!this.mobile) {
                this.$message.error("请填写手机号");
                return false;
            }

            if (!_test.mobile(this.mobile)) {
                this.$message.error("手机号格式不正确");
                return false;
            }

            let params = {}
            params[this.apiMobileName] = this.mobile

            let res = await this.$http.get(this.api, params);
            if (res.code == 200) {
               this.$message.success("发送成功");
               this.codeValue = 60;
               this.codeStatus = 1;
               this.timeFun = setInterval(() => {
                    if (this.codeValue <= 0) {
                        this.codeStatus = 0;
                        clearInterval(this.timeFun);
                        return false;
                    }
                    this.codeValue = this.codeValue - 1;
                }, 1000);
            } else {
                window.$msg.error(res.message);
            }
        },
    },
};
</script>
